package com.patch.update;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import com.patch.AppUpdate;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.pedant.SweetAlert.SweetAlertDialog;


public class UpdateTask extends AsyncTask<String, Void, Void> {

    private ProgressDialog progressDialog;
    private final int mType;
    private final WeakReference<Context> weakContext;//避免内存泄漏
    private String description;
    public static final int AUTO = 1;
    public static final int MANU = 0;
    public String DOWNLOAD_URL = "EMPTY";
    public String PACKAGE_NAME = "EMPTY";
    public String APKPATH = "EMPTY";
    public String UPDATE_URL = "EMPTY";
    public String DOWNLOAD_PATCH_URL = "EMPTY";//差分包下载路径
    public String OLD_VERSION = "EMPTY";//上一个版本号
    public String VERSION_ID = "EMPTY";

    /**
     * @param type
     */

    // 下载应用存放全路径
    private String FILE_NAME;

    private String FILE_PATCH_NAME;

    public UpdateTask(int type, Context mContext, String packageNmae, String apkPath, String updateUrl) {
        this.weakContext = new WeakReference<>(mContext);
        mType = type;
        APKPATH = apkPath;
        PACKAGE_NAME = packageNmae;
        UPDATE_URL = updateUrl;
        FILE_NAME = apkPath + File.separator + "app.apk";
        FILE_PATCH_NAME = apkPath + File.separator + "my.patch";
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Context context = weakContext.get();
        if (context == null) {
            // Context 已被回收，停止操作
            return;
        }
        if (mType == 0) {
            progressDialog = new ProgressDialog(context);
            progressDialog.setCancelable(false);
            progressDialog.setTitle("检查更新");
            progressDialog.setIcon(android.R.drawable.ic_dialog_alert);
            progressDialog.setMessage("正在检查更新，请等待...");
            progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    cancel(true);
                    Toast.makeText(context, "检查更新失败", Toast.LENGTH_LONG).show();
                }
            });
            progressDialog.show();
        }
    }

    @Override
    protected Void doInBackground(String... params) {
        try {
            String url = UPDATE_URL;
            getVersionId(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        Context context = weakContext.get();
        if (context == null) {
            // Context 已被回收，停止操作
            return;
        }
        if (DOWNLOAD_URL.equals("EMPTY")) {
            if (mType == 0) {
                progressDialog.dismiss();
                new AlertDialog.Builder(context)
                        .setTitle("警告")
                        .setMessage("检查更新失败，请检查网络设置！")
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
            }
        } else {
            String versionID = AppUpdate.getInstance().getVersion(context);
            if (versionID != null) {
                if (versionID.compareTo(VERSION_ID) < 0) {//服务器的版本号大于本机获取版本号
                    if (mType == 0) {
                        progressDialog.dismiss();
                    }
                    AlertDialog alertDialog = new AlertDialog.Builder(context)
                            .setTitle("软件版本更新")
                            .setMessage("检查到有新版本更新，建议您下载\n更新内容 :\n" + description)
                            .setPositiveButton("下载", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    new UpdateAppManager(context, APKPATH, PACKAGE_NAME, DOWNLOAD_URL, DOWNLOAD_PATCH_URL, OLD_VERSION).execute();
                                }
                            }).setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create();
                    alertDialog.show();
                    alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(v -> {
                        boolean haveInstallPermission = true;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            //先获取是否有安装未知来源应用的权限
                            try {
                                haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                            } catch (Exception e) {
                                String message = e.getMessage();
                                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
                            }
                            if (!haveInstallPermission) {//没有权限
                                installApk();
                            }
                        }
                        if (haveInstallPermission) {
                            alertDialog.dismiss();
                            new UpdateAppManager(context, APKPATH, PACKAGE_NAME, DOWNLOAD_URL, DOWNLOAD_PATCH_URL, OLD_VERSION).execute();
                        }
                    });
                } else {
                    if (mType == 0) {
                        progressDialog.dismiss();
                        new AlertDialog.Builder(context)
                                .setTitle("提示")
                                .setMessage("您是最新版本，无需更新！")
                                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }).create().show();
                    } else {
                        try {
                            File file = new File(FILE_NAME);
                            if (file.exists()) {
                                file.delete();
                            }
                            File file1 = new File(FILE_PATCH_NAME);
                            if (file1.exists()) {
                                file1.delete();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                if (mType == 0) {
                    progressDialog.dismiss();
                    new AlertDialog.Builder(context)
                            .setTitle("警告")
                            .setMessage("获取版本号失败，请检查是否给予软件许可！")
                            .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                }
            }
        }
    }

    private void installApk() {
        Context context = weakContext.get();
        if (context == null) {
            // Context 已被回收，停止操作
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先获取是否有安装未知来源应用的权限
            boolean haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {//没有权限
                new SweetAlertDialog(context)
                        .setTitleText("提示")
                        .setContentText("安装应用需要打开未知来源权限，请去设置中开启权限")
                        .setCancelText("取消")
                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                            }
                        })
                        .setConfirmText("去开启")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                                Uri packageURI = Uri.fromParts("package", PACKAGE_NAME, null);
                                //注意这个是8.0新API
                                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                                context.startActivity(intent);
                            }
                        }).show();
            }
        }
    }

    private void getVersionId(String Url) throws IOException {
        HttpURLConnection con = null;
        try {
            URL url = new URL(Url);
            con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(10000);
            con.setReadTimeout(15000);
            con.setRequestMethod("GET");
            con.setRequestProperty("client", "app");
            InputStream inputStream = con.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inputStream.close();
            byte[] data = outStream.toByteArray();
            String jsonString = new String(data);
            JSONObject jsonObj;
            jsonObj = new JSONObject(jsonString);
            JSONObject d = jsonObj.getJSONObject("data");
            VERSION_ID = d.getString("version");
            DOWNLOAD_URL = d.getString("downurl");
            try {
                DOWNLOAD_PATCH_URL = d.getString("patchPath");
                OLD_VERSION = d.getString("oldVersion");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            description = d.getString("description").replace("|", "\n");
        } catch (Exception e) {
            Log.e("版本更新", "最新版本:" + e);
        } finally {
            if (con != null)
                con.disconnect();
        }
    }

}
